package com.tyqx.hashchainbiz.service.impl;

import com.mongodb.client.gridfs.GridFSBucket;
import com.mongodb.client.gridfs.model.GridFSUploadOptions;
import com.tyqx.hashchainbean.module.HashChainStatistics;
import com.tyqx.hashchainbean.vo.MongoDbInfoVO;
import com.tyqx.hashchainbiz.service.HashChainStatisticsService;
import com.tyqx.hashchaindao.mapper.HashChainStatisticsMapper;
import com.tyqx.hashchainutil.common.mongodb.MongoDBUtil;
import org.bson.types.ObjectId;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.InputStream;
import java.util.List;

@Service("hashChainStatisticsService")
public class HashChainStatisticsServiceImpl implements HashChainStatisticsService {

    @Resource
    private HashChainStatisticsMapper hashChainStatisticsMapper;


    @Resource
    private MongoDBUtil mongoDBUtil;



    @Override
    public int add(HashChainStatistics hashChainStatistics) {
        return hashChainStatisticsMapper.add(hashChainStatistics);
    }

    @Override
    public List<HashChainStatistics> selectCount() {
        return hashChainStatisticsMapper.selectCount();
    }

    @Override
    public double selectCountByUserNameAndDataType(String userName, String dataType) {
        return hashChainStatisticsMapper.selectCountByUserNameAndDataType(userName, dataType);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ObjectId insertDataCountAndMongoDBGridFS(HashChainStatistics hashChainStatistics, String fileName, InputStream inputStream, GridFSUploadOptions options, GridFSBucket gridFSFilesBucket) throws Exception {
        Integer flag=hashChainStatisticsMapper.add(hashChainStatistics);
        if (flag == 0){
            throw new Exception("record statistcs error");
        }
        ObjectId fileId = gridFSFilesBucket.uploadFromStream(fileName, inputStream, options);

        return fileId;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insertDataCountAndMongoDB(HashChainStatistics hashChainStatistics, String collName, MongoDbInfoVO mongoDbInfoVO) throws Exception {
        Integer flag=hashChainStatisticsMapper.add(hashChainStatistics);
        if (flag == 0){
            throw new Exception("record statistcs error");
        }
        mongoDBUtil.insertOne(collName,mongoDbInfoVO);
    }

    @Override
    public List<HashChainStatistics> selectCountGroupByDataType() {
        return hashChainStatisticsMapper.selectCountGroupByDataType();
    }
}
